package com.victualler.core.common.wapper;



import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import com.victualler.core.common.io.InterfaceOutputStream;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
 * @Aouthor Guoshichang
 * @Date 13:52 on 2018/4/8.
 * @Function 接口请求包装类
 */
public class CustomResponseWapper extends HttpServletResponseWrapper {

    private PrintWriter cachedWriter;
    private CharArrayWriter bufferedWriter;
    private InterfaceOutputStream outPutStream;
    private HttpServletResponse response;
    private int httpStatus;

    @Override
    public void setStatus(int sc) {
        super.setStatus(sc);
        httpStatus = sc;
    }


    /**
     * 获取http状态
     * @return
     */
    public int getStatus() {
        return httpStatus;
    }

    public CustomResponseWapper(HttpServletResponse response) {
        super(response);
        this.response = response;
        this.bufferedWriter = new CharArrayWriter();
        this.cachedWriter = new PrintWriter(this.bufferedWriter);
    }

    public PrintWriter getWriter() throws IOException {
        if (this.cachedWriter == null) {
            this.cachedWriter = new PrintWriter(new OutputStreamWriter(new InterfaceOutputStream(this.response), "utf-8"));
        }

        return this.cachedWriter;
    }

    public void flushBuffer() throws IOException {
        this.outPutStream.flush();
    }

    public ServletOutputStream getOutputStream() throws IOException {
        if (this.outPutStream == null) {
            this.outPutStream = new InterfaceOutputStream(this.response);
        }
        return this.outPutStream;
    }

    public String getResult() {
        return this.bufferedWriter.toString();
    }

    public void finishResponse() throws IOException {
        if (this.outPutStream != null) {
            this.outPutStream.close();
        }

        if (this.cachedWriter != null) {
            this.cachedWriter.close();
        }

    }

}
